/*
 * Chrowety
 * lightbox.js
*/

// optimized

(function( D ){
	
	function $Q( i )
	{
		return D.querySelector(i);
	}
	
	function $C( el, attr )
	{
		return window.getComputedStyle( el, null ).getPropertyValue( attr );
	}

	lightBox = function( selector )
	{
		if( !$Q('#lightBoxBg') )
			lightBox.open( $Q( selector ) );	
	};
	
	lightBox.open = function( content )
	{
		( this.layer = D.createElement('div') ).setAttribute('id', 'lightBoxBg');
		
		this.layer.style.cssText = this.BgStyle();		
		
		( this.content = content ).style.cssText = this.ObjStyle( $C( this.content, 'width' ), $C( this.content, 'height' ) );
		
		D.body.appendChild(this.layer);
		
		window.addEventListener('resize', lightBox.resize);
		
		this.layer.addEventListener('click', function(){
			lightBox.close();
		});		
	};
	
	lightBox.close = function()
	{
		if( $Q('#lightBoxBg') )
		{
			D.body.removeChild(lightBox.layer);
			lightBox.content.style.cssText = '';
			lightBox.content = lightBox.layer = null;
			window.removeEventListener('resize', lightBox.resize);
		}	
	};
	
	lightBox.resize = function()
	{
		lightBox.layer.style.cssText = lightBox.BgStyle();
		lightBox.content.style.cssText = lightBox.ObjStyle( $C(lightBox.content, 'width' ), $C(lightBox.content, 'height') );		
	};
	
	lightBox.ObjStyle = function( width, height )
	{
		width = parseInt( width );
		height = parseInt( height );

		var 
		left = ( D.width - width ) / 2,
		top = ( D.height - height ) / 2;
				
		return (
			'display:block;'+
			'width: '+ width +'px;'+
			'height: '+( height ? height +'px' : 'auto' )+';'+
			'position:absolute;'+
			'top:0%;'+
			'left:0%;'+			
			'margin-top:'+ top +'px;'+
			'margin-left:'+ left +'px;'+
			'background-color:white;'+			
			'-webkit-transition:all 200ms ease-in-out;'+
			'-webkit-box-shadow:#ccc 0 0 10px, #555 0 0 30px;'+
			'border-radius:10px;'+
			'z-index:2;'
		);
	};
	
	lightBox.BgStyle = function( width, height )
	{
		return (
			'background-color: black;'+
			'display: block;'+
			'width: '+ D.width +'px;'+
			'height: '+ D.height +'px;'+
			'opacity: 0.5;'+
			'position:absolute;'+
			'top:0;'+
			'left:0;'+
			'-webkit-transition:all 200ms ease-in-out;'+
			'z-index:1;'
		);
	};
	
	window.onload = (function(){
		var 
		find = D.querySelectorAll('*[data-lightbox]'),
		n = find.length;
		
		while( n-- )
		{
			find[n].addEventListener('click', function(){
				lightBox( this.getAttribute('data-lightbox') );
			});
		}			
	});
})( document );